<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\CrmBottomMenu;
use app\model\CrmBottomMenuOriginal;

class CrmbottommenuController extends Base
{

	function index()
	{
		$weid = weid();
		$keyword = input('post.keyword', '', 'serach_in');
		$query = CrmBottomMenu::where(['weid' => weid()]);
		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$datalist = $query->order('sort asc,id asc')->select()->toArray();
        if (empty($datalist)) {
            $this->setbasedata();
			$datalist = $query->order('sort asc,id asc')->select()->toArray();
        }

		$data['data'] = $datalist;
		return $this->json($data);
	}

	public function setbasedata()
	{
		$weid = weid();
		$list = CrmBottomMenuOriginal::where(['weid' => '0'])->order('sort asc')->select()->toArray();
		if (!empty($list)) {
			foreach ($list as &$vo) {
				unset($vo['id']);
				$vo['weid'] = $weid;
			}
			$CrmBottomMenu = new CrmBottomMenu;
			$CrmBottomMenu->saveAll($list);
		}
	}

	function updateExt()
	{
		$postField = 'id,status,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		if (!$data['id']) throw new ValidateException('参数错误');
		CrmBottomMenu::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function add()
	{
		$postField = 'title,url,params,icon,iconactive,status,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		$data['weid'] = weid();

		try {
			$res = CrmBottomMenu::create($data);
			if ($res->id && empty($data['sort'])) {
				CrmBottomMenu::update(['sort' => $res->id, 'id' => $res->id]);
			}
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}

		return $this->json(['msg' => '添加成功', 'data' => $res->id]);
	}

	public function update()
	{
		$id = $this->request->post('id');
		if (empty($id)) {
			return $this->add();
		} else {
			$postField = 'id,title,url,params,icon,iconactive,status,sort';
			$data = $this->request->only(explode(',', $postField), 'post', null);
			try {
				CrmBottomMenu::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getUpdateInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$data = CrmBottomMenu::field('*')->find($id)->toArray();

		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		CrmBottomMenu::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
	function getField()
	{
		$data['urlarray'] = CrmBottomMenuOriginal::getpagearray();

		return $this->json(['data' => $data]);
	}
}
